import {Button, Drawer, Form, Modal, Row} from "antd";
import {useState} from "react";
import styles from './index.less'


const FormModal = (
  {
    title, // modal的标题,不传不显示标题
    visible, // 是否显示
    width, // 宽度,默认800
    isView,
    onVisibleChange, // visible改变回调
    onConfirm, // form确认事件,不传不显示按钮区域
    children, // form子项
    formRef, // ref
    initFormValue, // form默认值
    className,
    extraBtn, // 添加扩展按钮功能
    btnConfig,
    formLayout,
    titleExtra,
    submitFlag,
    labelCol, // label占Row比例,24基准
  }
) => {

  const [confirmLoading, setConfirmLoading] = useState(false);

  return (
    <Drawer
      className={`${className} ${styles.formModal} ${isView ? 'viewForm' : ''}`}
      title={title}
      width={width || 540}
      open={visible}
      onClose={() => {
        if (!confirmLoading) {
          onVisibleChange(false);
        }
      }}
      maskClosable={false}
      keyboard={!confirmLoading}
      closable={!confirmLoading}
      destroyOnClose={true}
      footer={null}
      extra={titleExtra}
    >
      <Form
        layout={formLayout || 'horizontal'}
        className={`${styles.formInModal} everyForm`}
        ref={formRef}
        initialValues={initFormValue}
        labelCol={{ span: labelCol || 6}}
        onFinish={async (values) => {
          if (!onConfirm) {
            return;
          }
          setConfirmLoading(true)
          const success = await onConfirm(values);
          setConfirmLoading(false)
          if (success) {
            onVisibleChange(false);
          }
        }}
      >
        {children}
        {(onConfirm || extraBtn) && (
          <div className={styles.btnWrap}>
            {onConfirm && (
              <>
                <Button
                  style={{ marginRight: 10 }}
                  disabled={confirmLoading}
                  onClick={() => onVisibleChange(false)}
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={confirmLoading}
                  disabled={submitFlag}
                >
                  {btnConfig && btnConfig.confirm ? btnConfig.confirm.text : '确认'}
                </Button>
              </>
            )}
            {extraBtn}
          </div>
        )}
      </Form>
    </Drawer>
  );
};


export default FormModal;